//
// Created by tang on 2022/5/15.
//

#include "data/editor_data.hpp"
#include "utils/date_utils.hpp"
#include "app/app_base.hpp"

#include <fmt/format.h>
#include <algorithm>

DayLevelNode::DayLevelNode (std::string date) : ExpandableNodeBase(move(date), &DayLevelNode::LoadItems) {}

void DayLevelNode::LoadItems ()
{
    auto items = App->Sql()->GetDailyItems(child_key);

    children.clear();
    std::ranges::transform(
            items,
            std::back_inserter(children),
            [](auto item) { auto id = item.work_id; return ItemNode{ std::move(item), App->Sql()->AllWorkItemTags(id) }; }
    );
}

MonthLevelNode::MonthLevelNode (std::string year, std::string month) :
        ExpandableNodeBase(fmt::format("{}-{}", year, month), &MonthLevelNode::LoadDays),
        year(move(year)), month(move(month)) {}

void MonthLevelNode::LoadDays ()
{
    auto days = App->Sql()->GetDayList(child_key);

    for (auto& d : days) {
        DayLevelNode node{ fmt::format("{}-{}", child_key, d) };
        node.title = fmt::format("{}年{}月{}日({})", year, month, d, ymd2week(year, month, d));
        children.emplace_back(node);
    }
}
YearLevelNode::YearLevelNode (std::string year) :
        ExpandableNodeBase<MonthLevelNode>(year, &YearLevelNode::LoadMonth),
        year(move(year)) {}

void YearLevelNode::LoadMonth ()
{
    auto ret = App->Sql()->GetMonthList(child_key);

    for (auto& m : ret) {
        MonthLevelNode node{ year, m };
        node.title = fmt::format("{}月", m);
        children.emplace_back(node);
    }
}

bool ItemNode::CanUpload() const {
    return !item.is_uploaded && item.issue_id > 0 && item.act_id > 0 &&
            item.hour > 0; // 未上传 且 设置了 关联问题 和 活动 且 时间大于0
}
